<template>
  <div class="color-picker">
    <div class="native-color-container">
      <input
        type="color"
        :value="value"
        @input="changeColorHandler($event.target?.value)"
      />
    </div>
    <ul class="picked-color-list">
      <li
        v-for="(color, index) in props.colors"
        @click.prevent="changeColorHandler(color)"
        :key="index"
        :class="`item-${index}`"
      >
        <div
          :style="{ backgroundColor: color }"
          class="color-item"
          v-if="color.startsWith('#')"
        ></div>
        <div class="color-item transparent-back" v-else></div>
      </li>
    </ul>
  </div>
</template>

<script setup lang="ts">
import type { PropType } from 'vue'
import { defaultColors } from './type/ColorPickerType'
//引入lodash-es节流函数
import { throttle } from 'lodash-es'
const props = defineProps({
  value: {
    type: String,
  },
  colors: {
    type: Array as PropType<string[]>,

    default: defaultColors,
  },
})

const emits = defineEmits(['change'])
const changeColorHandler = (value: string) => {
  throttle(() => {
    emits('change', value)
  }, 500)()
}
</script>

<style scoped>
.color-picker {
  display: flex;
}
.native-color-container {
  width: 40%;
}
.native-color-container input[type='color'] {
  width: 100%;
  cursor: pointer;
  height: 50px;
  border: 0;
  padding: 0;
  background-color: transparent;
}
.picked-color-list {
  padding: 0 0 0 5px;
  margin: 0;
  width: 60%;
  display: flex;
  list-style-type: none;
  flex-wrap: wrap;
  justify-content: space-between;
}
.picked-color-list li {
  flex: 1;
  width: 20%;
  min-width: 20%;
  max-width: 20%;
}
.color-item {
  padding: 3px;
  width: 20px;
  height: 20px;
  border-radius: 3px;
  margin-right: 5px;
  cursor: pointer;
  border: 1px solid #ccc;
}
.transparent-back {
  background: url('../assets/transparent.png') no-repeat;
}
</style>
